package com.sddnytsh.body_buildingsystem.services

import android.content.Context
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.net.Uri
import android.util.Log
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import okhttp3.*
import okhttp3.MediaType.Companion.toMediaType
import okhttp3.RequestBody.Companion.asRequestBody
import okhttp3.RequestBody.Companion.toRequestBody
import org.json.JSONObject
import java.io.ByteArrayOutputStream
import java.io.File
import java.io.FileOutputStream
import java.io.IOException
import java.util.concurrent.TimeUnit

/**
 * 头像服务类
 * 处理头像的上传、下载、缓存等功能
 */
class AvatarService(private val context: Context) {
    
    private val tag = "AvatarService"
    private val client = OkHttpClient.Builder()
        .connectTimeout(30, TimeUnit.SECONDS)
        .readTimeout(60, TimeUnit.SECONDS)
        .writeTimeout(60, TimeUnit.SECONDS)
        .retryOnConnectionFailure(true)
        .build()
    
    // 头像缓存目录
    private val avatarCacheDir = File(context.cacheDir, "avatars")
    
    init {
        // 创建头像缓存目录
        if (!avatarCacheDir.exists()) {
            avatarCacheDir.mkdirs()
        }
    }
    
    /**
     * 测试上传功能 - 使用最小的测试数据
     */
    suspend fun testUpload(userId: Long): Result<String> = withContext(Dispatchers.IO) {
        try {
            Log.d(tag, "开始测试上传 - userId: $userId")
            
            // 创建一个最小的测试图片
            val testBitmap = Bitmap.createBitmap(1, 1, Bitmap.Config.ARGB_8888)
            testBitmap.setPixel(0, 0, android.graphics.Color.RED)
            
            val byteArray = bitmapToByteArray(testBitmap)
            val base64Data = android.util.Base64.encodeToString(byteArray, android.util.Base64.NO_WRAP)
            
            Log.d(tag, "测试数据 - 文件大小: ${byteArray.size}, Base64长度: ${base64Data.length}")
            
            val jsonObject = JSONObject().apply {
                put("userId", userId)
                put("fileName", "test_${System.currentTimeMillis()}.jpg")
                put("contentType", "image/jpeg")
                put("fileSize", byteArray.size)
                put("base64Data", base64Data)
            }
            
            val jsonBody = jsonObject.toString()
            Log.d(tag, "测试请求JSON: $jsonBody")
            
            val requestBody = jsonBody.toRequestBody("application/json; charset=utf-8".toMediaType())
            
            val url = "${com.sddnytsh.body_buildingsystem.config.NetworkConfig.BASE_URL}/api/avatar/upload"
            val request = Request.Builder()
                .url(url)
                .post(requestBody)
                .addHeader("Content-Type", "application/json; charset=utf-8")
                .addHeader("ngrok-skip-browser-warning", "true")
                .build()
            
            client.newCall(request).execute().use { response ->
                val responseBody = response.body?.string()
                Log.d(tag, "测试响应 - 状态码: ${response.code}, 响应: $responseBody")
                
                if (response.isSuccessful) {
                    val avatarUrl = parseAvatarUrlFromJson(responseBody)
                    Result.success(avatarUrl ?: "test_success")
                } else {
                    Result.failure(Exception("测试失败: ${response.code} - $responseBody"))
                }
            }
        } catch (e: Exception) {
            Log.e(tag, "测试上传异常: ${e.message}", e)
            Result.failure(e)
        }
    }

    /**
     * 上传头像
     */
    suspend fun uploadAvatar(userId: Long, bitmap: Bitmap): Result<String> = withContext(Dispatchers.IO) {
        try {
            Log.d(tag, "开始上传头像 - userId: $userId")
            Log.d(tag, "原始图片尺寸: ${bitmap.width}x${bitmap.height}")
            
            // 压缩图片
            val compressedBitmap = compressBitmap(bitmap)
            val byteArray = bitmapToByteArray(compressedBitmap)
            
            Log.d(tag, "压缩后图片尺寸: ${compressedBitmap.width}x${compressedBitmap.height}")
            Log.d(tag, "压缩后文件大小: ${byteArray.size} bytes")
            
            // 转换为Base64 - 使用NO_WRAP避免换行符问题
            val base64Data = android.util.Base64.encodeToString(byteArray, android.util.Base64.NO_WRAP)
            Log.d(tag, "Base64数据长度: ${base64Data.length}")
            Log.d(tag, "Base64数据前100字符: ${base64Data.take(100)}")
            
            // 使用JSONObject构建请求体，避免手动拼接JSON
            val fileName = "avatar_${userId}_${System.currentTimeMillis()}.jpg"
            val jsonObject = JSONObject().apply {
                put("userId", userId)
                put("fileName", fileName)
                put("contentType", "image/jpeg")
                put("fileSize", byteArray.size)
                put("base64Data", base64Data)
            }
            
            val jsonBody = jsonObject.toString()
            Log.d(tag, "请求JSON长度: ${jsonBody.length}")
            Log.d(tag, "请求JSON前200字符: ${jsonBody.take(200)}")
            
            val requestBody = jsonBody.toRequestBody("application/json; charset=utf-8".toMediaType())
            Log.d(tag, "请求体大小: ${requestBody.contentLength()}")
            
            // 创建请求
            val url = "${com.sddnytsh.body_buildingsystem.config.NetworkConfig.BASE_URL}/api/avatar/upload"
            Log.d(tag, "请求URL: $url")
            
            val request = Request.Builder()
                .url(url)
                .post(requestBody)
                .addHeader("Content-Type", "application/json; charset=utf-8")
                .addHeader("ngrok-skip-browser-warning", "true")
                .build()
            
            Log.d(tag, "请求头: ${request.headers}")
            
            // 执行请求
            client.newCall(request).execute().use { response ->
                Log.d(tag, "响应状态码: ${response.code}")
                Log.d(tag, "响应头: ${response.headers}")
                
                val responseBody = response.body?.string()
                Log.d(tag, "响应体: $responseBody")
                
                if (response.isSuccessful) {
                    Log.d(tag, "头像上传成功: $responseBody")
                    
                    // 解析响应获取头像URL
                    val avatarUrl = parseAvatarUrlFromJson(responseBody)
                    if (avatarUrl != null) {
                        Log.d(tag, "解析到头像URL: $avatarUrl")
                        // 缓存头像到本地
                        cacheAvatarLocally(userId, compressedBitmap)
                        Result.success(avatarUrl)
                    } else {
                        Log.e(tag, "解析头像URL失败，响应体: $responseBody")
                        Result.failure(Exception("解析头像URL失败"))
                    }
                } else {
                    Log.e(tag, "头像上传失败: ${response.code} - ${response.message}")
                    Log.e(tag, "错误响应体: $responseBody")
                    Result.failure(Exception("上传失败: ${response.code} - ${response.message}"))
                }
            }
        } catch (e: Exception) {
            Log.e(tag, "头像上传异常: ${e.message}", e)
            Result.failure(e)
        }
    }
    
    /**
     * 下载头像
     */
    suspend fun downloadAvatar(avatarUrl: String): Result<Bitmap> = withContext(Dispatchers.IO) {
        try {
            Log.e(tag, "开始下载头像: $avatarUrl")
            
            val request = Request.Builder()
                .url(avatarUrl)
                .addHeader("Cache-Control", "no-cache, no-store, must-revalidate")
                .addHeader("Pragma", "no-cache")
                .addHeader("Expires", "0")
                .build()
            
            client.newCall(request).execute().use { response ->
                if (response.isSuccessful) {
                    val inputStream = response.body?.byteStream()
                    if (inputStream != null) {
                        val bitmap = BitmapFactory.decodeStream(inputStream)
                        if (bitmap != null) {
                            Log.e(tag, "头像下载成功，尺寸: ${bitmap.width}x${bitmap.height}")
                            Result.success(bitmap)
                        } else {
                            Result.failure(Exception("解析头像失败"))
                        }
                    } else {
                        Result.failure(Exception("响应体为空"))
                    }
                } else {
                    Log.e(tag, "头像下载失败: ${response.code}")
                    Result.failure(Exception("下载失败: ${response.code}"))
                }
            }
        } catch (e: Exception) {
            Log.e(tag, "头像下载异常: ${e.message}")
            Result.failure(e)
        }
    }
    
    /**
     * 获取本地缓存的头像
     */
    fun getCachedAvatar(userId: Long): Bitmap? {
        val avatarFile = File(avatarCacheDir, "avatar_$userId.jpg")
        return if (avatarFile.exists()) {
            try {
                BitmapFactory.decodeFile(avatarFile.absolutePath)
            } catch (e: Exception) {
                Log.e(tag, "读取缓存头像失败: ${e.message}")
                null
            }
        } else {
            null
        }
    }
    
    /**
     * 缓存头像到本地
     */
    private fun cacheAvatarLocally(userId: Long, bitmap: Bitmap) {
        try {
            val avatarFile = File(avatarCacheDir, "avatar_$userId.jpg")
            val outputStream = FileOutputStream(avatarFile)
            bitmap.compress(Bitmap.CompressFormat.JPEG, 90, outputStream)
            outputStream.close()
            Log.d(tag, "头像缓存成功: ${avatarFile.absolutePath}")
        } catch (e: Exception) {
            Log.e(tag, "头像缓存失败: ${e.message}")
        }
    }
    
    /**
     * 压缩图片
     */
    private fun compressBitmap(bitmap: Bitmap): Bitmap {
        val maxSize = 1024 // 增加最大尺寸到1024像素，提高图片质量
        val width = bitmap.width
        val height = bitmap.height
        
        return if (width > maxSize || height > maxSize) {
            val scale = minOf(maxSize.toFloat() / width, maxSize.toFloat() / height)
            val newWidth = (width * scale).toInt()
            val newHeight = (height * scale).toInt()
            Bitmap.createScaledBitmap(bitmap, newWidth, newHeight, true)
        } else {
            bitmap
        }
    }
    
    /**
     * 将Bitmap转换为ByteArray
     */
    private fun bitmapToByteArray(bitmap: Bitmap): ByteArray {
        val outputStream = ByteArrayOutputStream()
        bitmap.compress(Bitmap.CompressFormat.JPEG, 95, outputStream) // 提高压缩质量到95%
        return outputStream.toByteArray()
    }
    
    /**
     * 解析头像URL（从JSON响应）
     */
    private fun parseAvatarUrlFromJson(responseBody: String?): String? {
        return try {
            if (responseBody != null) {
                Log.d(tag, "开始解析响应: $responseBody")
                val jsonObject = org.json.JSONObject(responseBody)
                
                // 检查success字段
                val success = jsonObject.optBoolean("success", false)
                Log.d(tag, "响应success字段: $success")
                
                if (success) {
                    val data = jsonObject.getJSONObject("data")
                    Log.d(tag, "data对象: $data")
                    
                    // 尝试获取avatarUrl
                    val avatarUrl = data.optString("avatarUrl", null)
                    Log.d(tag, "解析到的avatarUrl: $avatarUrl")
                    
                    if (avatarUrl.isNullOrEmpty()) {
                        Log.e(tag, "avatarUrl为空或null")
                        null
                    } else {
                        avatarUrl
                    }
                } else {
                    Log.e(tag, "响应success为false")
                    null
                }
            } else {
                Log.e(tag, "响应体为null")
                null
            }
        } catch (e: Exception) {
            Log.e(tag, "解析头像URL失败: ${e.message}", e)
            null
        }
    }
    
    /**
     * 解析头像URL
     */
    private fun parseAvatarUrl(responseBody: String?): String? {
        return try {
            // 简单的JSON解析，实际项目中可以使用Gson
            if (responseBody != null && responseBody.contains("avatarUrl")) {
                val startIndex = responseBody.indexOf("\"avatarUrl\":\"") + 12
                val endIndex = responseBody.indexOf("\"", startIndex)
                if (startIndex > 11 && endIndex > startIndex) {
                    responseBody.substring(startIndex, endIndex)
                } else {
                    null
                }
            } else {
                null
            }
        } catch (e: Exception) {
            Log.e(tag, "解析头像URL失败: ${e.message}")
            null
        }
    }
    
    /**
     * 清理缓存
     */
    fun clearCache() {
        try {
            avatarCacheDir.listFiles()?.forEach { file ->
                if (file.isFile) {
                    file.delete()
                }
            }
            Log.d(tag, "头像缓存已清理")
        } catch (e: Exception) {
            Log.e(tag, "清理缓存失败: ${e.message}")
        }
    }
    
    /**
     * 获取缓存大小
     */
    fun getCacheSize(): Long {
        return try {
            avatarCacheDir.listFiles()?.sumOf { it.length() } ?: 0L
        } catch (e: Exception) {
            0L
        }
    }
}
